package models

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"strconv"
	"time"
)

func AddTopic(title, content string) error {
	o := orm.NewOrm()
	topic := Topic{
		Title:     title,
		Content:   content,
		Created:   time.Now(),
		Updated:   time.Now(),
		ReplyTime: time.Now(),
	}
	_, err := o.Insert(&topic)
	if err != nil {
		beego.Error(err)
	}
	return err
}

func AllTopic(isDesc bool) ([]*Topic, error) {
	o := orm.NewOrm()
	topic := make([]*Topic, 0)
	qs := o.QueryTable("topic")
	var err error
	if isDesc {
		_, err = qs.OrderBy("-created").All(&topic)
	} else {
		_, err = qs.All(&topic)
	}
	if err != nil {
		beego.Error(err)
	}
	return topic, err
}

func GetTopic(tid string) (*Topic, error) {
	id, err := strconv.ParseInt(tid, 10, 64)
	if err != nil {
		beego.Error(err)
	}
	o := orm.NewOrm()
	var topic Topic
	err = o.QueryTable("topic").Filter("id", id).One(&topic)
	if err != nil {
		beego.Error(err)
		return nil, err
	}

	// 浏览次数+1
	topic.Views++
	_, err = o.Update(&topic)
	return &topic, err
}

func ModifyTopic(tid, title, content string) error {
	id, err := strconv.ParseInt(tid, 10, 64)
	if err != nil {
		beego.Error(err)
		return err
	}
	o := orm.NewOrm()
	topic := &Topic{Id: id}
	if o.Read(&topic) != nil {
		topic.Title = title
		topic.Content = content
		topic.Updated = time.Now()
		_, err = o.Update(&topic)
	}
	return err
}
